package com.atguigu.gmall.payment.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author: atguigu
 * @create: 2023-08-12 15:25
 */
@RestController
@RequestMapping("/api/payment")
public class AlipayController {


    @Autowired
    private AlipayService alipayService;

    /**
     * 调用支付方接口生成支付表单
     *
     * @param orderId
     * @return
     */
    @GetMapping("/alipay/submit/{orderId}")
    public String createAlipayForm(HttpServletRequest request, @PathVariable("orderId") Long orderId) {
        String userId = AuthContextHolder.getUserId(request);
        return alipayService.createAlipayForm(userId, orderId);
    }


    /**
     * 处理支付宝同步回调请求
     * @param response
     */
    @GetMapping("/alipay/callback/return")
    public void sendRedictPaySuccessReq(HttpServletResponse response) throws IOException {
        //重定向到支付成功页面
        response.sendRedirect(AlipayConfig.return_order_url);
    }


    /**
     * 处理支付宝异步回调（支付宝通知支付系统告知用户支付结果）
     * @param mapParam
     * @return
     */
    @PostMapping("/alipay/callback/notify")
    public String notifyPaySuccess(@RequestParam Map mapParam){
        String retStr = alipayService.notifyPaySuccess(mapParam);
        return retStr;
    }

    /**
     * 测试接口，用于支付宝退款
     * @param outTradeNo 订单编号
     * @return
     */
    @GetMapping("/alipay/refund/{outTradeNo}")
    public Result refund(@PathVariable("outTradeNo") String outTradeNo){
        alipayService.refund(outTradeNo);
        return Result.ok();
    }
}
